package com.guanyong.webapi.controllers.api;


import com.guanyong.model.UserBaseModel;
import com.guanyong.model.UserInfoModel;
import com.guanyong.services.UserBaseService;
import com.guanyong.services.UserInfoService;
import com.guanyong.utils.Comm.*;
import com.guanyong.utils.LogHelper.LogHelper;
import com.guanyong.utils.NetUtils.CookieUtils;
import com.guanyong.utils.NetUtils.UploadFileUtil;
import com.guanyong.webapi.config.SMSUtil;
import com.guanyong.webapi.config.SmsModel;
import com.guanyong.webapi.handle.GlobleData;
import com.guanyong.webapi.handle.TokenHelper;
import com.guanyong.webapi.handle.UploadFileType;
import com.guanyong.webapi.handle.UserHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by mxk on 2017/5/29.
 */

@RestController
@RequestMapping("/api/user/")
public class UserApi {
    @Autowired
    UserBaseService userBaseService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    UploadFileUtil uploadFileUtil;

    @Autowired
    UserHandle userHandle;

    @Autowired
    GlobleData globleData;

    @Value("${mortise.VerifyCode.cache.codekey}")
    String mortisecacheVerfiCode;
    @Value("${mortise.usercas.cookie.loginName}")
    String mortiseloginName;

    @Value("${mortise.usercas.cookie.loginToken}")
    String mortiseloginToken;

    @Autowired
    TokenHelper tokenHelper;

    @Autowired
    SMSUtil smsUtil;

    @RequestMapping(value = "updateusername", method = RequestMethod.POST)
    public ResultObject<Integer> UpdateUserName(HttpServletRequest request,
                                                String userName){
        ResultObject<Integer> resultObject=new ResultObject<Integer>();
        UserBaseModel userBaseModel = userHandle.getCurUser(request);
        if (userBaseModel != null && !userBaseModel.getfId().equals("")) {
            resultObject= userBaseService.updateUserName(userBaseModel.getfId(),userName);
        }
        else{
            resultObject.setCode(ResultCode.NoLogin);
        }
        return resultObject;
    }

    @RequestMapping(value = "updateusername1_0", method = RequestMethod.POST)
    public ResultObject<String> UpdateUserName1_0(HttpServletRequest request,
                                                  String userName){
        ResultObject<String> resultObject=new ResultObject<String>();
        UserBaseModel userBaseModel = userHandle.getCurUser(request);
        if (userBaseModel != null && !userBaseModel.getfId().equals("")) {
            resultObject= userBaseService.updateUserName1_0(userBaseModel.getfId(),userName);
        }
        else{
            resultObject.setCode(ResultCode.NoLogin);
        }
        return resultObject;
    }

    @RequestMapping(value = "updatephoto", method = RequestMethod.POST)
    public ResultObject<String> UpdatePhoto( HttpServletRequest request,
                                              @RequestParam(value = "photo",required = true) MultipartFile photo){
        ResultObject<String> resultObject=new ResultObject<String>();
        String path  =null;
        UserBaseModel userBaseModel = userHandle.getCurUser(request);
        DataInputStream dataStream =null;
        InputStream in=null;
        try {
            ServletInputStream sin= request.getInputStream();
            dataStream = new DataInputStream(request.getInputStream());
            in = (InputStream)dataStream;
//            request.getReader();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (userBaseModel != null && !userBaseModel.getfId().equals("")) {
            try {
                    path = uploadFileUtil.SaveFileByMultiFlie(photo,request,UploadFileType.Photo);
//                    path = uploadFileUtil.SaveFileByMultiFlie1_0(dataStream,request,UploadFileType.Photo);
            } catch (Exception e) {
                e.printStackTrace();
                resultObject.setCode(ResultCode.OperateFail);
            }
            if (!path.equals("")) {
                resultObject = userBaseService.updatePhoto1_0(userBaseModel.getfId(), path);
            } else {
                resultObject.setCode(ResultCode.ServiceError);
            }
        }
        else{
            resultObject.setCode(ResultCode.NoLogin);
        }
        return resultObject;
    }



    @RequestMapping(value = "updatephotoIOS", method = RequestMethod.POST)
    public ResultObject<String> UpdatePhotoIOS( HttpServletRequest request,
                                                @RequestBody MultipartFile photo){
        ResultObject<String> resultObject=new ResultObject<String>();
        String path  =null;
        UserBaseModel userBaseModel = userHandle.getCurUser(request);
        DataInputStream dataStream =null;
        InputStream in=null;
        try {
            dataStream = new DataInputStream(request.getInputStream());


        } catch (IOException e) {
            e.printStackTrace();
        }
        if (userBaseModel != null && !userBaseModel.getfId().equals("")) {
            try {
                    path = uploadFileUtil.SaveFileByMultiFlie(photo,request,UploadFileType.Photo);
//                path = uploadFileUtil.SaveFileByMultiFlieIOS(dataStream,request,UploadFileType.Photo);
            } catch (Exception e) {
                e.printStackTrace();
                resultObject.setCode(ResultCode.OperateFail);
            }
            if (!path.equals("")) {
                resultObject = userBaseService.updatePhoto1_0(userBaseModel.getfId(), path);
            } else {
                resultObject.setCode(ResultCode.ServiceError);
            }
        }
        else{
            resultObject.setCode(ResultCode.NoLogin);
        }
        return resultObject;
    }


    @RequestMapping(value = "updateuserinfo", method = RequestMethod.POST)
    public ResultObject<UserInfoModel> UpdateUserinfo(HttpServletRequest request,
                                                String sex,
                                                String introduction,
                                                Date birthday){

        ResultObject<UserInfoModel> resultObject=new ResultObject<UserInfoModel>();
        UserBaseModel userBaseModel = userHandle.getCurUser(request);
        if (userBaseModel != null && !userBaseModel.getfId().equals("")) {
            UserInfoModel userInfoModel = new UserInfoModel();
            userInfoModel.setfId(userBaseModel.getfId());
            userInfoModel.setfBirthday(birthday);
            userInfoModel.setfSex(sex);
            userInfoModel.setfIntroduction(introduction);
            Integer res = userInfoService.UpdateUserinfo(userInfoModel);
            if (res > -1) {
                resultObject.setCode(ResultCode.OperateOk);
                resultObject.setResult(userInfoModel);
            } else {
                resultObject.setCode(ResultCode.OperateFail);
            }
        }
        else{
            resultObject.setCode(ResultCode.NoLogin);
        }
        return  resultObject;
    }

    @RequestMapping(value = "getuserinfo", method = RequestMethod.GET)
    public ResultObject<UserInfoModel> GetUserinfoById(HttpServletRequest request){

        ResultObject<UserInfoModel> resultObject=new ResultObject<UserInfoModel>();
        UserBaseModel userBaseModel = userHandle.getCurUser(request);
        if (userBaseModel != null && !userBaseModel.getfId().equals("")){
            UserInfoModel userInfoModel=  userInfoService.GetUserInfoModelById(userBaseModel.getfId());
            if (userInfoModel!=null) {
                resultObject.setResult(userInfoModel);
            }
            else{
                resultObject.setCode(ResultCode.NoLogin);
            }
        }
        else{
            resultObject.setCode(ResultCode.NoLogin);
        }

        return  resultObject;
    }

    /**
     * 用户信息写入cookie
     * @param rememberMe 是否记住登录帐号
     * @param loginName 登录账号
     * @param user 登录或注册之后的用户对象
     * @param reponse
     * @param request
     * @return
     */
    ResultObject<Boolean> writeUserCookie(boolean rememberMe,
                                          String loginName,
                                          UserBaseModel user,
                                          HttpServletResponse reponse,
                                          HttpServletRequest request){
        ResultObject<Boolean> resultObject=new ResultObject<Boolean>();        //是否记住用户名
        if(rememberMe) {
            CookieUtils.addCookie(reponse, mortiseloginName, loginName, 0, "", "");
        }else {
            CookieUtils.delCookie(request,reponse, mortiseloginToken);
        }
        //生成令牌信息，每次访问鉴别身份
        tokenHelper.setCasToken(user.getfId(),user.getfPassword(),reponse,request);
        return resultObject;
    }


    @RequestMapping(value = "loginuser", method = RequestMethod.POST)
    public ResultObject<UserBaseModel> LoginUser(HttpServletRequest request,
                                                 HttpServletResponse reponse,
                                                 String phone,
                                                 String password,
                                                 Integer loginapp){
        ResultObject<UserBaseModel> result = null;
        //判断验证码
        try {
            String ip=com.guanyong.utils.NetUtils.IPUtil.getIpAddr(request);
            //登录验证
            result = userBaseService.UserLogin(phone, password,2,ip,loginapp);
            //登录验证通过
            if (result.getCode().equals(ResultCode.LoginSucess)) {
                //写如cookie
                writeUserCookie(false,phone,result.getResult(),reponse,request);
            }
            //登录验证失败
            else if (result.getCode().equals(ResultCode.LoginFail)) {
                LogHelper.logger().info("登录验证失败：登录账号：" + phone + "，登录密码：" + password + "，失败原因：" + result.getCode().toString());
                result = new ResultObject<UserBaseModel>();
                //所有验证失败的情况都返回密码错误，防止恶意猜测密码
                result.setCode(ResultCode.LoginFail);
                result.setErrorMsg("手机号未注册");
            }else{
                LogHelper.logger().info("登录验证失败：登录账号：" + phone + "，登录密码：" + password + "，失败原因：" + result.getCode().toString());
                result = new ResultObject<UserBaseModel>();
                //所有验证失败的情况都返回密码错误，防止恶意猜测密码
                result.setCode(ResultCode.LoginPassError);
                result.setErrorMsg("账号或密码错误");
            }
        } catch (Exception ex) {//登录验证发生异常

            if (result == null) {
                result = new ResultObject<UserBaseModel>();
                result.setCode(ResultCode.ServiceError);
            }
            LogHelper.logger().error(ex.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "loginout", method = RequestMethod.POST)
    public ResultObject<Integer> LoginOut(HttpServletRequest request,
                                          HttpServletResponse reponse){
        ResultObject<Integer> result = new ResultObject<Integer>();
        tokenHelper.delMyCasToken(request,reponse);
        return result;
    }

    //用户注册
    @RequestMapping(value = "reguser", method = RequestMethod.POST)
    public ResultObject<UserBaseModel> RegUser(HttpServletRequest request,
                                               HttpServletResponse reponse,
                                               String phone,
                                               @RequestParam String phoneSN,
                                               String password,
                                               String code,
                                               Integer regapp){
        // code 验证
        ResultObject<UserBaseModel> resultObject=new ResultObject<UserBaseModel>();
        HashMap<String,SmsModel> smsMap =   smsUtil.getSmsModelMap();
        SmsModel smsModel = smsMap.get(phoneSN);
        if (smsModel!=null){
            if (smsModel.getNumber().equals(code)){
                if (smsModel.getInitTime().getTime() + 15*60*1000>new Date().getTime()){
                    String userName= RandomValue.getChineseName();
                    resultObject=userInfoService.RegUser(phone,password,
                            globleData.DefaultPhotoPath,
                            userName,
                            "",
                            "",
                            "",
                            "男",//默认注册为男
                            regapp);
                    if (resultObject.getCode().equals(ResultCode.OperateOk)){
                        //写入cookie
                        writeUserCookie(false,phone,resultObject.getResult(),reponse,request);
                    }
                }else {
                    resultObject.setCode(ResultCode.ServiceError);
                    resultObject.setErrorMsg("服务器操作失败");
                }
                smsMap.remove(phoneSN);
            }else {
                resultObject.setCode(ResultCode.CehckCodeError);
                resultObject.setErrorMsg("验证失败");
            }
        }
        else{
            resultObject.setCode(ResultCode.ServiceError);
            resultObject.setErrorMsg("服务器没有接到请求重新发送短信");
        }
        return  resultObject;
    }



    @RequestMapping(value = "regusernocheck", method = RequestMethod.POST)
    public ResultObject<UserBaseModel> RegUser2(HttpServletRequest request,
                                               HttpServletResponse reponse,
                                               String phone,
                                               String password,
                                               String code,
                                               Integer regapp){
        // code 验证
        ResultObject<UserBaseModel> resultObject=new ResultObject<UserBaseModel>();
        String userName= RandomValue.getChineseName();
        resultObject=userInfoService.RegUser(phone,password,
                globleData.DefaultPhotoPath,
                userName,
                "",
                "",
                "",
                "男",//默认注册为男
                regapp);
        if (resultObject.getCode().equals(ResultCode.OperateOk)){
            //写入cookie
            writeUserCookie(false,phone,resultObject.getResult(),reponse,request);
        }
        return  resultObject;
    }


    @RequestMapping(value = "updatephone", method = RequestMethod.POST)
    public ResultObject<Integer> UpdatePhone(HttpServletRequest request,
                                             String phone,
                                             @RequestParam String phoneSN,
                                             String code){

        ResultObject<Integer> resultObject = new ResultObject<Integer>();

        UserBaseModel userBaseModel = userHandle.getCurUser(request);
        if (userBaseModel != null && !userBaseModel.getfId().equals("")) {
            HashMap<String, SmsModel> smsMap = smsUtil.getSmsModelMap();
            SmsModel smsModel = smsMap.get(phoneSN);
            if (smsModel != null) {
                if (smsModel.getNumber().equals(code)) {
                    if (smsModel.getInitTime().getTime() + 15 * 60 * 1000 > new Date().getTime()) {
                        resultObject = userBaseService.updatePhone(userBaseModel.getfId(),phone);

                    } else {
                        resultObject.setCode(ResultCode.ServiceError);
                        resultObject.setErrorMsg("服务器操作失败");
                    }
                    smsMap.remove(phoneSN);
                } else {
                    resultObject.setCode(ResultCode.CehckCodeError);
                    resultObject.setErrorMsg("验证失败");
                }
            } else {
                resultObject.setCode(ResultCode.ServiceError);
                resultObject.setErrorMsg("服务器没有接到请求重新发送短信");
            }
        }
        else{
            resultObject.setCode(ResultCode.NoLogin);
        }
        return  resultObject;
    }


    @RequestMapping(value = "loginbyopenid", method = RequestMethod.POST)
    public ResultObject<UserBaseModel> LoginByOpenid(HttpServletRequest request,
                                                     HttpServletResponse reponse,
                                                     Integer type,
                                                     String openid,
                                                     String nick,
                                                     String photo,
                                                     String sex,//添加 sex
                                                     Integer regapp){
        ResultObject<UserBaseModel> resultObject=new ResultObject<UserBaseModel>();
        String ip=com.guanyong.utils.NetUtils.IPUtil.getIpAddr(request);
        resultObject=userBaseService.LoginUserByOpenId(type,openid,nick,photo,sex,ip,regapp);
        if (resultObject!=null){
            if (resultObject.getCode().equals(ResultCode.OperateOk)|| resultObject.getCode()
                    .equals(ResultCode.LoginSucess)){
                //写入cookie
                writeUserCookie(false,openid,resultObject.getResult(),reponse,request);
            }
        }

        return resultObject;
    }

    @RequestMapping(value = "bindingopenid", method = RequestMethod.POST)
    public ResultObject<UserBaseModel> BindingOpenid(HttpServletRequest request,
                                                     HttpServletResponse reponse,
                                                     Integer type,
                                                     String openid,
                                                     String nick,
                                                     String photo,
                                                     String sex,//添加 sex
                                                     Integer regapp){
        ResultObject<UserBaseModel> resultObject=new ResultObject<UserBaseModel>();
        String ip=com.guanyong.utils.NetUtils.IPUtil.getIpAddr(request);
        UserBaseModel userBaseModel = userHandle.getCurUser(request);
        if (userBaseModel != null && !userBaseModel.getfId().equals("")) {
            userBaseService.bindingOpenid(userBaseModel,type,openid,nick,photo,sex,ip,regapp);
        }
        return resultObject;
    }






    //用户修改密码
    @RequestMapping(value = "updatepwd", method = RequestMethod.POST)
    public ResultObject<Integer> RegUser(HttpServletRequest request,
                                         HttpServletResponse reponse,
                                         String password,
                                         String code){
        // code 验证
        ResultObject<Integer> resultObject=new ResultObject<Integer>();
        UserBaseModel userBaseModel = userHandle.getCurUser(request);
        if (userBaseModel != null && !userBaseModel.getfId().equals("")) {

            resultObject=userBaseService.updatePwd(userBaseModel.getfId(),password);
        }
        else{
            resultObject.setCode(ResultCode.NoLogin);
        }
        return  resultObject;
    }




    @RequestMapping(value = "forgetpwd", method = RequestMethod.POST)
    public ResultObject<Integer> ForGetPwd(HttpServletRequest request,
                                               HttpServletResponse reponse,
                                               String phone,
                                               @RequestParam String phoneSN,
                                               String password,
                                               String code){
        // code 验证
        ResultObject<Integer> resultObject=new ResultObject<Integer>();
        resultObject=userBaseService.forgetPwd(phone,password);
        HashMap<String,SmsModel> smsMap =   smsUtil.getSmsModelMap();
        SmsModel smsModel = smsMap.get(phoneSN);
        if (smsModel!=null){
            if (smsModel.getNumber().equals(code)){
                if (smsModel.getInitTime().getTime() + 15*60*1000>new Date().getTime()){
                    resultObject=userBaseService.forgetPwd(phone,password);
                }else {
                    resultObject.setCode(ResultCode.ServiceError);
                    resultObject.setErrorMsg("服务器操作失败");
                }
                smsMap.remove(phoneSN);
            }else {
                resultObject.setCode(ResultCode.CehckCodeError);
                resultObject.setErrorMsg("验证失败");
            }
        }
        else{
            resultObject.setCode(ResultCode.ServiceError);
            resultObject.setErrorMsg("服务器没有接到请求重新发送短信");
        }
        return  resultObject;
    }


}
